import { Service } from 'egg';
const { Op } = require('sequelize');

export default class Test extends Service {
  // 获取所有角色
  public async getRolesList(obj) {
    const currentPage = parseInt(obj.currentPage) || 1; // 当前页
    const pageSize = parseInt(obj.pageSize) || 5; // 页容量
    const { key } = obj;
    // 关键字条件
    const defaultCondtion = {
      [Op.or]: [
        { roleName: { [Op.substring]: key } },
        { roleDesc: { [Op.substring]: key } },
      ],
    };
    if (key) {
      const roles = await this.ctx.model.Role.findAll({
        attributes: {
          exclude: [ 'createdAt', 'updatedAt' ],
        },
        where: defaultCondtion,
        limit: pageSize, // 取多少条
        offset: (currentPage - 1) * pageSize, // 跳过多少条
      });
        // 总条数
      const count = await this.ctx.model.Role.findAndCountAll({
        where: defaultCondtion,
      });
      return { roles, count: count.count };
    }
    // 没有关键字则输出全部
    const roles = await this.ctx.model.Role.findAll({
      attributes: {
        exclude: [ 'createdAt', 'updateAt' ],
      },
      limit: pageSize, // 取多少条
      offset: (currentPage - 1) * pageSize, // 跳过多少条
    });
      // 总条数
    const count = await this.ctx.model.Role.findAndCountAll();
    return { roles, count: count.count };
  }
  public async createRoles(obj) {
    const { roleName } = obj;
    console.log('111111111111111111');
    if (roleName) {
      const role = await this.ctx.model.Role.findOne({
        where: {
          roleName,
        },
      });
      if (role) {
        throw new Error('角色已存在');
      }
    }
    // 加入数据库
    const data = await this.ctx.model.Role.create(obj);
    const roleData = data.dataValues;
    return roleData;
  }
}
